import html
import re
from typing import List

from langchain_core.messages import BaseMessage
from langchain_core.utils import print_text


def unescape_html(val: str) -> str:
    if not val:
        return val
    try:
        return html.unescape(val)
    except Exception as e:
        return val

def replace_file_search_fix(val: str) -> str:
    if not val:
        return val
    try:
        result = re.sub(r'^<<<<<<<\s*SEARCH.*$', '<<<<<<< SEARCH', val, flags=re.MULTILINE)
        return result
    except Exception as e:
        print('replace_file_search_fix error', e)
        return val

def print_message(messages: List[BaseMessage]):
    for msg in messages:
        print_text(text=f"<<{msg.type}>>\n", color="red")
        print_text(text=f"{msg.content}\n", color="green")

def dict_to_json_str(d: dict) -> str:
    items = []
    for k, v in d.items():
        if isinstance(v, str):
            items.append(f'"{k}": "{v}"')
        elif v is None:
            items.append(f'"{k}": null')
        elif isinstance(v, bool):
            items.append(f'"{k}": {str(v).lower()}')
        else:
            items.append(f'"{k}": {v}')
    return '{' + ', '.join(items) + '}'